<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Form{
var $atributosForm;
var $cadenaForm;
var $cadenaInput;
var $cadenaDiv;
var $cadenaLabel;
var $myForm;
var $myBodyForm;
var $validaciones;
var $validacionesBody;
var $temporalValidacion;
var $cadenaTextArea;
var $tamanhoTabla;


function Form(){
	$CI =& get_instance();
	$CI->load->library('globalvar');
	$arreglo=$CI->globalvar->getPropForm();
	$tamanho=$arreglo['tamanho'];
	$this->tamanhoTabla=$CI->globalvar->getPropForm();
	//$this->inicializarAtributosForm();
	
	
	
	}
	
#####
function addCampo($tipo,$labelText,$atributos,$validacion=""){
	
	//$atributos es un array
	$this->createCampo($tipo,$labelText,$atributos);
	
	
		if($atributos['id']!=''){
			if($validacion!=''){
				$this->addValidacion($atributos["id"],$validacion);
			}
		}
	
	}

function addCampoDefault($tipo,$labelText,$atributos,$validacion=""){
	$atributos=$this->addDefault($atributos);
	$this->createCampo($tipo,$labelText,$atributos);
	
	
		if($atributos['id']!=''){
			if($validacion!=''){
				$this->addValidacion($atributos["id"],$validacion);
			}
		}
	
	}
	
function addCampoDefaultHtml($html,$arregloId,$arregloValidacion){
	$this->createCampoHtml($html);
	for($i=0;$i<count($arregloId);$i++){
	if($arregloId[$i]!=''){
		if($arregloValidacion[$i]!=''){
			$this->addValidacion($arregloId[$i],$arregloValidacion[$i]);
			}
		}
	}
	}

function addCamposVariosDefault($atributos){
	
	}


function addSelectDefault($tipo,$labelText,$atributos,$validacion="",$arregloValue=NULL,$value='',$seleccione=true){
	$atributos['class']='class:form-control chzn-select';
	$atributos=$this->addDefault($atributos);
	$this->createCampo($tipo,$labelText,$atributos,$arregloValue,$value);
	
	
		if($atributos['id']!=''){
			if($validacion!=''){
				$this->addValidacion($atributos["id"],$validacion);
			}
		}
	
	}
function addSelectNormalDefault($tipo,$labelText,$atributos,$validacion="",$arregloValue=NULL,$value='',$seleccione=true){
	$atributos['class']='form-control';
	$atributos=$this->addDefault($atributos);
	$this->createCampo($tipo,$labelText,$atributos,$arregloValue,$value,$seleccione);
	
	
	if($atributos['id']!=''){
			if($validacion!=''){
				$this->addValidacion($atributos["id"],$validacion);
			}
		}
	
	}

function addSubmit($atributos){
	$this->createSubmit($atributos);
	
	}

function addSubmitVarios($atributos){
	
	$this->createSubmitVarios($atributos);
	
	}
	
function addHidden($atributos){
	$this->createHidden($atributos);
	
	}

####	

function addDefault($atributos){
	
	$CI =& get_instance();
	$CI->load->library('globalvar');
	
	$newArreglo=$CI->globalvar->getPropInput();
	if(isset($atributos['id']))
	if($atributos['name']=='') $atributos['name']=$atributos['id'];
	$atributos=$CI->globalvar->addValueOfArray($newArreglo,$atributos);
	
	return $atributos;
	
		
	}


function addValidacion($id,$validacion){

	$val=$id.": {
                ";
	$val.=$validacion;
	$val.='
	},';
	
	$this->validacionesBody.=$val;
	}

function addValidacionMessage($id,$label,$validacion){

	$val=$id.": {
                ";
	$val.=$this->createMessage($label,$validacion);
	$val.='
	},';
	
	$this->validacionesBody.=$val;
	}

function verificarTransformar($atributte){
	$at=$this->stringToArray($attribute);

		if($CI->service->verificaIndice($at['value'])){
			return true;
			}else return false;

	
	
	}

function createAtributos($atributos){
	$CI =& get_instance();
	$CI->load->library('service');
	$cadena='';
	
		while ($nameKey = current($array)) {
			$cadena.=' '.$nameKey.'="'.$atributos[$nameKey].'"';
			next($array);
		}
	
		return $cadena;
	}

function createForm($atributos){
	
	$cadena='<form';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>
	#contentForm#
	</form>
	';
	
	$this->myForm=$cadena;
	
	//validaciones
	$this->validaciones="$(function() {
       $.validator.addMethod('selectNone', function(value, element) {
      	return	 parseFloat(value) > 0;
},'Este campo es obligatorio');

$.validator.addMethod('compara2', function(value, element,param) {
	if(isNaN(parseFloat($(param).val())) && isNaN(parseFloat(value))) return false;
	else{
		if(!isNaN(parseFloat($(param).val()))) return true;
		else
			if(!isNaN(parseFloat(value))) return true; else return false;
		}
},'Debe seleccionar uno');

			
		formValidation();
		
      });
	  function formValidation(){
	  $('#".$atributos["id"]."').validate({
		  ignore: [], // <-- option so that hidden elements are validated
		  rules:{
        #contentValidacion#
		  }
		  ,
        errorClass: 'help-block',
        errorElement: 'span',
        highlight: function(element, errorClass, validClass) {
            $(element).parents('.form-group').removeClass('has-success').addClass('has-error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.form-group').removeClass('has-error').addClass('has-success');
        }
    });
	  }";	
	
}

function createLabel($atributos){
	
	$cadena='<label';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>#contentLabel#</label>
	';
	return $cadena;
}

function createInput($atributos){
	
	$cadena='<input';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>';
	return $cadena;
}

function createTextArea($atributos,$value){
	
	$cadena='<textarea';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>'.$value.'</textarea>';
	return $cadena;
}


function cuerpoFile2($isReadOnly,$value){
	$v='';
	$r='';
	if($isReadOnly==true) 
	$r='';
	else
	$r='<span class="btn btn-default btn-file"><span class="fileinput-new">Seleccione Imagen</span><span class="fileinput-exists">Change</span>
                                <input type="file" name="userfile">
                              </span>
                              <a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>';
					  
	if($value!='')
	$v='<img src="'.base_url().'application/views/upload/'.$value.'" />';
	
	$cadena='<div class="form-group">
                        <label class="control-label col-lg-4">Imagen</label>
                        <div class="col-lg-8">
                          <div class="fileinput fileinput-new" data-provides="fileinput">
                            <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;">'.$v.'</div>
                            <div>
                              '.$r.'
                            </div>
                          </div>
                        </div>
                      </div>';
return $cadena;
	}


function createSelect($atributos,$arreglo,$value='',$seleccione=true){
	
	$cadena='<select';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>
	';
	if($seleccione)
	$cadena.='<option value="">Seleccione</option>
	';
	for($i=0;$i<count($arreglo);$i++){
		//if(isset($value))
		//var_dump($arreglo);
		if(strtolower($arreglo[$i]['value'])==strtolower($value)) $d='selected'; else $d='';
	$cadena.='<option value="'.$arreglo[$i]['value'].'" '.$d.' >'.$arreglo[$i]['option'].'</option>
	';
	}
	$cadena.='</select>';
	return $cadena;
}

function createDiv($atributos){
	
	$cadena='<div';
	$cadena.=$this->createAtributos($atributos);
	$cadena.='>
	#contentDiv#
	</div>
	';
	return $cadena;
	}
	
function createContenedor($nameForm,$contenido){
	$cadena='<div class="col-lg-'.$this->tamanhoTabla.'">
	<div class="box">
 <header>
  <h5>'.$nameForm.'</h5>
 </header>
 <div class="body" style="min-height:300px">'.$contenido.'</div>
</div>
</div>';
				return $cadena;
	
	}
	
function isReadOnly($atributos){
	
	if($atributos['readOnly']!='readonly') return false; else return true;
}

function obtenerValue2($atributos){
	
	if($atributos['value']=='asociado/' || $atributos['value']=='inquilino/') return false; else return $atributos['value'];
	
	return false;
}
function createCampo($tipo,$labelText,$atributos,$arregloValue=NULL,$value='',$seleccione=true){
	$CI =& get_instance();
	$CI->load->library('globalvar');
	
	$arregloDiv1=$CI->globalvar->getPropDiv();
	$arregloDiv2=$CI->globalvar->getPropDiv();
	$arregloLabel=$CI->globalvar->getPropLabel();
	
	$arregloDiv1['id']="dv_".$id;
	
	
	//if($tipo=='file2'){
		//$div1=$this->cuerpoFile2($this->isReadOnly($atributos),$this->obtenerValue2($atributos));
		//}else{
	$id=$this->obtenerId($atributos);		
	$div1=$this->createDiv($arregloDiv1);
	$label=$this->createLabel($arregloLabel);
	$div2=$this->createDiv($arregloDiv2);
	$campo=$this->inputType($tipo,$atributos,$arregloValue,$value,$seleccione);
	
	$label=$this->replace("#contentLabel#",$labelText,$label);
	
	$div2=$this->replace("#contentDiv#",$campo,$div2);
	$div2=$label.$div2;
	
	$div1=$this->replace("#contentDiv#",$div2,$div1);
	//}
	$this->myBodyForm.=$div1;
	
	}
function createCampoHtml($html){
	$this->myBodyForm.=$html;
	}

function createSubmit($atributos){
	$CI =& get_instance();
	$CI->load->library('globalvar');
	
	$arregloDiv=$CI->globalvar->getPropDiv();
	$arregloDiv['class']="form-actions no-margin-bottom";
	
	$div=$this->createDiv($arregloDiv);
	$campo=$this->inputType('submit',$atributos);
	$div=$this->replace("#contentDiv#",$campo,$div);
	
	$this->myBodyForm.=$div;
	
	}

function createSubmitVarios($atributos){
	$CI =& get_instance();
	$CI->load->library('globalvar');
	
	$arregloDiv=$CI->globalvar->getPropDiv();
	$arregloDiv['class']="form-actions no-margin-bottom";
	
	$div=$this->createDiv($arregloDiv);
	
	$campo='';
	for($i=0;$i<count($atributos);$i++){
	$campo.=$this->inputType('submit',$atributos[$i]);
	$campo.=' &nbsp;';
	}
	$div=$this->replace("#contentDiv#",$campo,$div);
	
	$this->myBodyForm.=$div;
	
	}

function createHidden($atributos){
	$CI =& get_instance();
	$CI->load->library('globalvar');
	
	$arregloDiv=$CI->globalvar->getPropDiv();
	$arregloDiv['class']="form-actions no-margin-bottom";
	
	$div=$this->createDiv($arregloDiv);
	
	$campo='';
	for($i=0;$i<count($atributos);$i++)
	$campo.=$this->inputType('hidden',$atributos[$i]);
	
	$div=$this->replace("#contentDiv#",$campo,$div);
	
	$this->myBodyForm.=$div;
	
	}

function printForm($nameForm="Formulario"){
	$print=$this->createContenedor($nameForm,$this->replace("#contentForm#",$this->myBodyForm,$this->myForm));
	$this->createTemporalValidacion();
	echo $print;
	}

function returnForm($nameForm="Formulario"){
	$print=$this->createContenedor($nameForm,$this->replace("#contentForm#",$this->myBodyForm,$this->myForm));
	$this->createTemporalValidacion();
	return $print;
	}
	
function createTemporalValidacion(){
	$this->temporalValidacion=$this->replace("#contentValidacion#",trim($this->validacionesBody,","),$this->validaciones);
	}
function printValidacion(){
	
	echo $this->temporalValidacion;
	
	}
function returnValidacion(){
	
	return $this->temporalValidacion;
	
	}


function stringToArray($string){
	$atributos=explode(",",$string);
	//var_dump($atributos);
	for($i=0;$i<count($atributos);$i++){
		$atributos0=explode(':',$atributos[$i]);
		if($atributos0[0]=='value'){
			$aux=str_replace("value:","",$atributos[$i]);
			$aux2=str_replace(":","#dospuntos#",$aux);
			$atributos[$i]='value:'.$aux2;	

			}
		$atributos[$i]=str_replace("http://","http#//",$atributos[$i]);
		$atributos[$i]=str_replace("javascript:","javascript#",$atributos[$i]);
		
		$a=explode(":",$atributos[$i]);
		
		//var_dump($a[1]);
		if(isset($a[1]))
		$arreglo[$a[0]]=str_replace("#dospuntos#",":",$a[1],$count);
		if($count==0 && isset($a[1]))
		$arreglo[$a[0]]=str_replace("http#//","http://",$a[1]);
		if($count==0)
		$arreglo[$a[0]]=str_replace("javascript#","javascript:",$arreglo[$a[0]]);
		
	}
		return $arreglo;
}
function replace($busca,$reemplazo,$donde){
	return str_replace($busca,$reemplazo,$donde);
	}
	
function inputType($tipo,$atributos,$arregloValue=NULL,$value='',$seleccione=true){
	switch($tipo){
		case 'text': 		$casilla=$this->createInput($atributos);break;
		case 'url': 		$casilla=$this->createInput($atributos);break;
		case 'date': 		$casilla=$this->createInput($atributos);break;
		case 'password': 	$casilla=$this->createInput($atributos);break;
		case 'email': 		$casilla=$this->createInput($atributos);break;
		case 'checkbox': 	$casilla=$this->createInput($atributos);break;
		case 'hidden': 		$casilla=$this->createInput($atributos);break;
		case 'file': 		$casilla=$this->createInput($atributos);break;
		case 'textarea': 	$casilla=$this->createTextArea($atributos,$this->obtenerValue($cadena));break;
		case 'select':		$casilla=$this->createSelect($atributos,$arregloValue,$value,$seleccione);break;
		case 'submit': 		$casilla=$this->createInput($atributos);break;
		
		
		
		}
		return $casilla;
	}	


function obtenerValue($cadena){
	return $atributos['value'];
	
}

function obtenerId($atributos){
	return $atributos['id'];
	
	
}

	/*function inicializarAtributosForm(){
		$this->cadenaForm="id,name,action,method,enctype,accept,onSubmit,onReset,class";
		$this->cadenaInput="type,class,style,name,id,value,size,readOnly,disabled,onfocus,onblur,onselect,onchange,onClick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup,data-placeholder,tabindex,data-size";
		$this->cadenaTextArea="type,class,style,name,id,title,lang,dir,cols,rows,size,readOnly,disabled,tabindex,accesskey,onfocus,onblur,onselect,onchange,onclick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup";
		$this->cadenaDiv="class,id,style,title,dir,lang,align,,onclick,ondblclick,onmousedown,onmouseup,onmouseover,onmousemove,onmouseout,onkeypress,onkeydown,onkeyup";
		$this->cadenaLabel="class";
	}*/
	
#################Esto requiere implementacion para mensajes personalizados#############################	
	
	function createMessage($label,$validaciones){
		$validacion=explode(',',$validaciones);
		for($i=0;$i<count($validacion);$i++){
			$v=explode(':',$validacion[$i]);
			switch($v[0]){
				case 'required': 	$v[1]=$this->myMessage($label,0);break;
				case 'remote': 		$v[1]=$this->myMessage($label,1);break;
				case 'minlength': 	$v[1]=$this->myMessage($label,2,$v[1]);break;
				case 'maxlength':	$v[1]=$this->myMessage($label,3,$v[1]);break;
				case 'rangelength':	$cad=str_replace('[','',$v[1]);
									$cad=str_replace(']','',$cad);
									$v2=explode(',',$cad);
									$v[1]=$this->myMessage($label,3,$v2[0],$v2[1]);break;
				case 'min':			break;
				case 'max':			break;
				case 'range':		break;
				case 'email':		break;
				case 'url':			break;
				case 'date':		break;
				case 'dateISO':		break;
				case 'number':		break;
				case 'digits':		break;
				case 'credicard':	break;
				case 'equalto':		break;
				}
			}
		}
	
	function myMessage($label='',$tipo='',$value1='',$value2=''){
		
		}
		
		
	##########################################################################
	##########################################################################
	##########################################################################
	
	
	function constructForm($mode,$formForm,$formData,$formSubmit,$formHidden){
		$CI =& get_instance();
        $CI->load->library('dbconfiguration');
		$etiquetas=$CI->dbconfiguration->getEtiquetas();
		
        $this->createForm($formForm);
		while($name=key($formData)){
			
			switch($formData[$name]['type']){
				case 'text':	$this->addCampoDefault($formData[$name]['type'],$etiquetas[$formData[$name]['id']],$formData,$formData[$name]['validation']);
				break;
				
				case 'date':	$this->addCampoDefault($formData[$name]['type'],$etiquetas[$formData[$name]['id']],$formData,$formData[$name]['validation']);
				break;
				
				case 'email':	$this->addCampoDefault($formData[$name]['type'],$etiquetas[$formData[$name]['id']],$formData,$formData[$name]['validation']);
				break;
				
				case 'select':	$this->addSelectDefault($formData[$name]['type'],$etiquetas[$formData[$name]['id']],$formData,$formData[$name]['validation'],$formData[$name]['selectValues'],$formData[$name]['selectValue']);
				break;
				
				}
			
			next($formData);
			}
			######################## SUBMIT #############################
			$i=0;
			while($name=key($formSubmit)){
				$btnArray[$i]=array('type'=>$formSubmit['type'],
									'value' =>$formSubmit['value'],
									'class' =>$formSubmit['class'],
									'onclick' =>$formSubmit['onclick']);
				next($formSubmit);
				}
			$this->addSubmitVarios($btnArray);
			
			#############################################################
			
			
			######################## HIDDEN #############################
			$j=0;
			while($name=key($formHidden)){
				$hidden[$j]=array(	'type'=>$formHidden['type'],
									'id' =>$formHidden['id'],
									'value' =>$formHidden['value']);
				next($formHidden);
				}
			$this->addHidden($hidden);
			
			#############################################################
		
		}
	
	
	
	
	
}

?>